package com.zhangyu.shadow.repair.delegate.search;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.InputType;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.alibaba.fastjson.TypeReference;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.zhangyu.shadow.repair.R;
import com.zhangyu.shadow.repair.R2;
import com.zhangyu.shadow.repair.config.RepairItemType;
import com.zhangyu.shadow.repair.config.RequestUrls;
import com.zhangyu.shadow.repair.config.TroubleInfo;
import com.zhangyu.shadow.repair.delegate.search.entity.Trouble;
import com.zhangyu.shadow.repair.event.TroubleAddEvent;
import com.zhangyu.shadow.repair.manager.AccountManager;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import st.lib.base.delegate.RxShadowDelegate;
import st.lib.base.net.callback.IError;
import st.lib.base.net.callback.ISuccess;
import st.lib.base.net.rx.RxRestClient;
import st.lib.base.ui.recycler.BaseDecoration;
import st.lib.base.ui.recycler.MultipleField;
import st.lib.base.ui.recycler.MultipleItemEntity;
import st.lib.base.ui.recycler.ObjConverter;
import st.lib.base.ui.search.SearchClearEditText;
import st.lib.base.util.utilcode.util.ToastUtils;

import static com.zhangyu.shadow.repair.config.RepairItemType.ITEM_FINISH_PLAN;


/**
 * @author zhangyu
 * @date 2018/2/24
 */

public class AddTroubleDelegate extends RxShadowDelegate {
    private static final String ITEM_POSITION = "position";
    private static final String ITEM_LIST = "list";
    private static final String ITEM_NAME = "name";
    private static final String SEARCH_TYPE = "type";
    private static final String CLASSIFICATION_CODE = "classificationCode";

    public static AddTroubleDelegate create(int position,
                                            String name,
                                            int type,
                                            String code) {
        final AddTroubleDelegate contentDelegate = new AddTroubleDelegate();
        final Bundle bundle = new Bundle();
        bundle.putInt(ITEM_POSITION, position);
        bundle.putString(ITEM_NAME, name);
//        bundle.putSerializable(ITEM_LIST, list);
        bundle.putInt(SEARCH_TYPE, type);
        bundle.putString(CLASSIFICATION_CODE, code);
        contentDelegate.setArguments(bundle);
        return contentDelegate;
    }

    @BindView(R2.id.toolbar_search)
    Toolbar mToolbar;
    @BindView(R2.id.et_search)
    SearchClearEditText mEditTextSearch;
    @BindView(R2.id.tag_flow_layout)
    TagFlowLayout mTagFlowLayout;
    @BindView(R2.id.list_view_search_trouble)
    RecyclerView mListView;
    @BindView(R2.id.tv_name)
    TextView mTvName;
    TagAdapter<MultipleItemEntity> mTagAdapter;
    private AddTroubleAdapter mSearchDataAdapter;
    private List<MultipleItemEntity> mItemEntities = new ArrayList<>();
    private LayoutInflater mInflater;
    private int mPosition;
    private String mName;
    private int mType;
    private String mCode;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final Bundle bundle = getArguments();
        if (bundle != null) {
            mPosition = bundle.getInt(ITEM_POSITION);
            mName = bundle.getString(ITEM_NAME);
            mType = bundle.getInt(SEARCH_TYPE);
            mCode = bundle.getString(CLASSIFICATION_CODE);
            @SuppressWarnings("unchecked")
            ArrayList<MultipleItemEntity> list =
                    TroubleInfo.getInfos();
            if (list != null) {
                mItemEntities.addAll(list);
            }
        }
    }

    @Override
    public Object setLayout() {
        return R.layout.delegate_add_trouble;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        initView();
        initData();
    }

    private void initData() {
        mInflater = LayoutInflater.from(getContext());
        mTagAdapter = new TagAdapter<MultipleItemEntity>(mItemEntities) {
            @Override
            public View getView(FlowLayout parent, int position, MultipleItemEntity multipleItemEntity) {
                View view = mInflater.inflate(R.layout.item_trouble_content_tag2,
                        parent, false);
                TextView tv = view.findViewById(R.id.tv_content);
                tv.setText((CharSequence) multipleItemEntity.getField(MultipleField.NAME));
                return view;
            }
        };
        mTagFlowLayout.setAdapter(mTagAdapter);
        mTagFlowLayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                mItemEntities.remove(position);
                mTagAdapter.notifyDataChanged();
                return false;
            }
        });
        mSearchDataAdapter = new AddTroubleAdapter(R.layout.view_text, null);
        mListView.setAdapter(mSearchDataAdapter);
        mListView.setLayoutManager(new LinearLayoutManager(getContext()));
        mListView.addItemDecoration(BaseDecoration.create(_mActivity.getResources()
                .getColor(R.color.color_white), 1));
        mSearchDataAdapter.bindToRecyclerView(mListView);
        mSearchDataAdapter.setEmptyView(R.layout.view_list_empty, (ViewGroup) mListView.getParent());
        mListView.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                Trouble trouble = mSearchDataAdapter.getItem(position);
                mItemEntities.add(MultipleItemEntity.builder()
                        .setItemType(ITEM_FINISH_PLAN)
                        .setField(MultipleField.NAME, trouble != null ? trouble.getName() : null)
                        .setField(MultipleField.ID, trouble != null ? trouble.getId() : null)
                        .setField(RepairItemType.ITEM_CODE, trouble != null ? trouble.getCode() : null)
                        .setField(RepairItemType.ITEM_CLASSIFICATION_CODE, trouble != null ?
                                trouble.getClassificationCode() : null)
                        .setField(RepairItemType.ITEM_CLASSIFICATION_NAME, trouble != null ?
                                trouble.getClassificationCodeName() : null)
                        .build());
                mTagAdapter.notifyDataChanged();
            }
        });
    }

    private void initView() {
        mEditTextSearch.setHint("请输故障内容");
        mEditTextSearch.setInputType(InputType.TYPE_CLASS_TEXT);
        mEditTextSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                String key = mEditTextSearch.getText().toString();
                if (!key.isEmpty()) {
                    search(key, mCode);
                }
                return false;
            }
        });
        mTvName.setText(mName);
        initToolbarNav(mToolbar);
    }

    private void search(String key, String code) {
        mSearchDataAdapter.setEmptyView(R.layout.view_list_loading, (ViewGroup) mListView.getParent());
        mDisposables.add(RxRestClient.builder()
                .url(RequestUrls.URL_MAINTAIN_SEARCH_TROUBLE)
                .params("troubleName", key)
                .params(AccountManager.getInstance().getBaseInfo())
                .params("classificationCode", code)
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        if (mSearchDataAdapter != null) {
                            mSearchDataAdapter.setEmptyView(R.layout.view_list_empty, (ViewGroup) mListView.getParent());
                            ArrayList<Trouble> list = new ObjConverter<ArrayList<Trouble>>().convert(
                                    response, new TypeReference<ArrayList<Trouble>>() {
                                    }
                            );
                            mSearchDataAdapter.setNewData(list);
                        }
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        mSearchDataAdapter.setNewData(null);
                        mSearchDataAdapter.setEmptyView(R.layout.view_list_empty,
                                (ViewGroup) mListView.getParent());
                    }
                })
                .build()
                .post());
    }

    protected void initToolbarNav(Toolbar toolbar) {
        toolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pop();
            }
        });
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                int i = item.getItemId();
                if (i == R.id.menu_add) {
                    String content = mEditTextSearch.getText().toString();
                    if (content.isEmpty()) {
                        ToastUtils.showShortSafe("请输入故障内容!");
                    } else {
                        mItemEntities.add(MultipleItemEntity.builder()
                                .setItemType(ITEM_FINISH_PLAN)
                                .setField(MultipleField.NAME, content)
                                .setField(MultipleField.ID, 0)
                                .setField(RepairItemType.ITEM_CODE, "0")
                                .setField(RepairItemType.ITEM_CLASSIFICATION_CODE, mCode)
                                .setField(RepairItemType.ITEM_CLASSIFICATION_NAME, mName)
                                .build());
                        mTagAdapter.notifyDataChanged();
                        mEditTextSearch.setText(null);
                    }

                }
                return true;
            }
        });
        toolbar.inflateMenu(R.menu.add);
    }

    @OnClick(R2.id.button_confirm)
    public void onConfirm() {
        TroubleAddEvent event = new TroubleAddEvent(mItemEntities, mPosition);
        EventBus.getDefault().post(event);
        pop();
    }

    @Override
    public boolean onBackPressedSupport() {
        if (!isFastClick()) {
            pop();
        }
        return true;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }
}
